# -*- coding: utf-8 -*-
from chemdb import dbHandle

import hashlib

def login(db, host, username='', password=''):

	if not username or not password:
		dbHandle.reconnect('chemdb_min_user', 'origindb', db, host)
		dbHandle.setUid(-1)
		return

	hashPass = hashlib.md5(password)

	dbUid, dbPass = dbHandle.getUserInfo(username)

	if dbPass != hashPass.digest():
		raise ValueError, "Bad username / password"

	chemEncrypt = dbHandle.get('chem_pass', 'user', 'username', username)

	chemPass = crypt(chemEncrypt, int(hashPass.hexdigest(), 16))

	dbHandle.reconnect('chemdb_user', chemPass, db, host)
	dbHandle.setUid(dbUid)


def logout():
	dbHandle.reconnect('chemdb_min_user', 'origindb')
	dbHandle.setUid(-1)


def crypt (sequence, key):
	import random
	sign = (key > 0) * 2 - 1
	random.seed (abs (key * sign))
	s = ''
	for i in xrange (len (sequence)):
		r = random.randint (0, 255)
		s += chr ((ord (sequence [i]) + r * sign) % 256)
	return s
